package com.book.modules.aspect;

import com.book.common.api.entity.CurrentUser;
import com.book.common.util.RequestInfoUtil;
import com.book.modules.core.log.entity.LogInfo;
import com.book.modules.core.log.service.ILogInfoService;
import com.book.modules.helper.CurrentUserHelper;
import com.book.modules.util.HttpContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * AOP 记录用户操作日志
 *
 * Description：
 * @Author： leo.xiong
 * @CreateDate： 2019/8/13 16:29
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Value("${isOpenAopLog:false}")
    private Boolean isOpenAopLog;

    @Autowired
    private ILogInfoService logInfoService;

    @Autowired
    private CurrentUserHelper currentUserHelper;

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void pointcut() {
        // do nothing
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result;
        long beginTime = System.currentTimeMillis();
        // 执行方法
        result = point.proceed();
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        // 设置 IP地址
        String ip = RequestInfoUtil.getIpAddress(request);
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        LogInfo logInfo = new LogInfo();
        CurrentUser currentUser = currentUserHelper.getCurrentUser();
        if (currentUser != null) {
            logInfo.setUserId(currentUser.getId());
            logInfo.setUsername(currentUser.getUsername());
        }
        if (isOpenAopLog) {
            logInfo.setIp(ip);
            logInfo.setUseTime(time);
            logInfoService.saveLog(point, logInfo);
        }
        return result;
    }
}
